package saas.dev.webflux.webflux.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import saas.dev.webflux.webflux.domain.Good;
import saas.dev.webflux.webflux.generator.GoodGenerator;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * @ClassName : GoodHandler
 * @Author : y1
 * @Date: 2022/3/25 14:06
 * @Description :
 */
@Configuration
@Component
public class GoodHandler {
    private Flux<Good> goodList;

    public GoodHandler() {
        List<Good> goods = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            goods.add(new Good(finalI, "小米", "2000"));
        }
        goodList = Flux.fromIterable(goods);
    }

    public Mono<ServerResponse> hello(ServerRequest request) {
        return ok().contentType(MediaType.TEXT_PLAIN)
                .bodyValue("Hello Spring!");
    }

    public Mono<ServerResponse> echo(ServerRequest request) {
        return ok().contentType(MediaType.TEXT_EVENT_STREAM)
                .body(Flux.interval(Duration.ofSeconds(2)).map(i->DateUtil.now()), String.class);
//        return goodList.delayElements(Duration.ofMillis(2));
    }
}
